<?php
namespace app\common\Logic;
use think\Loader;
use think\Model;
use think\Db;
class ExportLogic{
	public $excelObj=null;					//PHPExcel对象
	public $sheetObj=null;					//当前工作sheet
	public $bisConfig=null;					//程序配置参数
	public $sheetIndex=0;					//当前PHPExcel的sheet索引
	public $id=null;						//引用主键id
	public $fieldTit=[];					//表字段
	public $cellArr=[];						//对应表字段的Excel列字母
	public $biss=[];						//桥梁数据
	public function __construct(){
		Loader::import('lib.PHPExcel');
		$this->excelObj=new \PHPExcel();
	}
	//导出项目及关联数据，$id项目数据主键
	public function exportBisAll($id){
		$this->id=$id;
		try{
			$this->createBis();
			$this->createBiss();
			$this->createBais();
		}catch(\Exception $e){
			$sheetObj=$this->sheetObj;
			
			$cellArr=$this->cellArr;
			$num=count($cellArr);
			$sheetObj->mergeCells('A2:'.$cellArr[$num-1].'2');
			$sheetObj->setCellValue('A2',$e->getMessage());
		}
//		show($this->biss);
		$this->export('项目及关联数据');
	}
	//导出项目及关联数据，$id项目数据主键
	public function exportBissAll($id){
		$this->id=$id;
		try{
			$this->createBiss();
			$this->createBais();
		}catch(\Exception $e){
			$sheetObj=$this->sheetObj;
			
			$cellArr=$this->cellArr;
			$num=count($cellArr);
			$sheetObj->mergeCells('A2:'.$cellArr[$num-1].'2');
			$sheetObj->setCellValue('A2',$e->getMessage());
		}
//		show($this->biss);
		$this->export('桥梁及关联数据');
	}
	//构建项目数据
	protected function createBis(){
		$this->bisConfig=config('bis.bis');
		$excelObj=$this->excelObj;
		$this->sheetObj=$excelObj->getActiveSheet();
		$this->sheetObj->setTitle('项目数据');
		
		$this->setHeadLine();
		$this->setBodyLine();
		$this->sheetIndex++;
	}
	//构建桥梁数据
	protected function createBiss(){
		$this->bisConfig=config('bis.biss');
		$excelObj=$this->excelObj;
		
		if($this->sheetIndex==0){						//如果直接导出桥梁
			$this->sheetObj=$excelObj->getActiveSheet();
			$this->sheetObj->setTitle('桥梁数据');
			$this->setHeadLine();
			$this->setBodyLine();
		}else{											//选择项目导出
			$excelObj->createSheet();  						//创建新的sheet
			$excelObj->setactivesheetindex(1);  			//设置sheet队列的第二个为当前工作sheet
			$this->sheetObj=$excelObj->getActiveSheet();
			$this->sheetObj->setTitle('桥梁数据');
			$this->setHeadLine();
			$this->setBodysLine();
		}
		$this->sheetIndex++;
	}
	//构建BAIS数据
	protected function createBais(){
		$this->bisConfig=config('bis.comp');
		$excelObj=$this->excelObj;
		
		if($this->sheetIndex==1){						//直接导出桥梁
			$excelObj->createSheet();
			$excelObj->setactivesheetindex(1);
			$this->sheetObj=$excelObj->getActiveSheet();
			$this->sheetObj->setTitle('BAIS数据');
			$this->setHeadLine();
			$this->setBodysLine();
		}else{
			$excelObj->createSheet();  					//创建新的sheet
			$excelObj->setactivesheetindex(2);  		//设置sheet队列的第二个为当前工作sheet
			$this->sheetObj=$excelObj->getActiveSheet();
			$this->sheetObj->setTitle('BAIS数据');
			$this->setHeadLine();
			$this->setLeveBodysLine();
		}
	}
	//设置头数据
	protected function setHeadLine(){
		$sheetObj=$this->sheetObj;
		$bisConfig=$this->bisConfig;
		$biss=$this->biss;
		$fieldTit=$this->getHeadField();
		if(empty($biss)){
			$this->cellArr=$cellArr=getAZ702(count($fieldTit));									//数据总条数
			foreach($fieldTit as $k1=>$v1){
				$cell=$cellArr[$k1];
				if($cell!='A') $sheetObj->getColumnDimension($cell)->setWidth(18);
				$sheetObj->setCellValue($cell.'1',$v1['Comment']);					//设置头行内容
			}
			$sheetObj->getStyle('A1:'.$cellArr[count($fieldTit)-1].'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
			$sheetObj->getStyle('A1:'.$cellArr[count($fieldTit)-1].'1')->getFont()->setBold(true);
		}else{
			$this->cellArr=$cellArr=getAZ702(count($fieldTit)+1);					//数据总条数
			array_unshift($fieldTit,['Comment'=>'桥梁主键','Field'=>'linkproid']);
			foreach($fieldTit as $k1=>$v1){
				$cell=$cellArr[$k1];
				if($cell!='A' && $cell!='B') $sheetObj->getColumnDimension($cell)->setWidth(18);
				$sheetObj->setCellValue($cell.'1',$v1['Comment']);					//设置头行内容
			}
			$sheetObj->getStyle('A1:'.$cellArr[count($fieldTit)-1].'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::VERTICAL_CENTER); //设置单元格内容水平对齐
			$sheetObj->getStyle('A1:'.$cellArr[count($fieldTit)-1].'1')->getFont()->setBold(true);		//设置字体为粗体
		}
		
		$this->fieldTit=$fieldTit;
	}
	/**
	 * 构建单条数据主体
	 */
	protected function setBodyLine(){
		$sheetObj=$this->sheetObj;
		$bisConfig=$this->bisConfig;
		$fieldTit=$this->fieldTit;			//当前字段数据
		$id=$this->id;
		$cellArr=$this->cellArr;			//当前字母数组
		$rel=Db::table('think_pro_'.$bisConfig['nid'])->where('id',$id)->find();
		if(!$rel){
			throw new \Exception("无项目数据");
		}
		foreach($fieldTit as $k3=>$v3){
			$cell=$cellArr[$k3];
			if($v3['Field'] == 'uid'){
				$cellValue=Db::name('member')->where('id',$rel[$v3['Field']])->value('contact');
			}elseif($v3['linkproid'] ==-1){
				if($v3['htmltype']=='radio'){
					$cellValue=Db::name('member')->where('id',$rel[$v3['Field']])->value('contact');
				}else{
					$members=Db::name('member')->where('id in ('.$rel[$v3['Field']].')')->column('contact');
					$cellValue=implode(',', $members);
				}
			}elseif($v3['htmltype']=='checkbox'){
				$cellValue=implode(',', json_decode($rel[$v3['Field']],true));
			}elseif($v3['htmltype']=='datetime' || $v3['Field']=='create_time'){
				$cellValue=date('y-m-d H:i:s',$rel[$v3['Field']]);
			}elseif($v3['Field']=='status'){
				$cellValue=getProgramStat($rel[$v3['Field']]);
			}else{
				$cellValue=$rel[$v3['Field']];
			}
			$sheetObj->setCellValue($cell.'2',$cellValue);
		}
	}
	protected function setBodysLine(){
		$sheetObj=$this->sheetObj;
		$bisConfig=$this->bisConfig;
		$fieldTit=$this->fieldTit;
		$id=$this->id;
		$cellArr=$this->cellArr;			//由头行数据生成
		$rel=Db::table('think_pro_'.$bisConfig['nid'])->where('linkproid',$id)->select();
		if(!$rel){
			throw new \Exception("无数据");
		}
		$biss=[];
		array_walk($rel,function($val) use(&$biss){
			$biss[]=$val['id'];
		});
		
		$this->biss=$biss;
		foreach($rel as $k2=>$v2){	//每一次循环为一行数据
			$num=$k2+2;
			foreach($fieldTit as $k3=>$v3){
				$cell=$cellArr[$k3];
				if($v3['Field'] == 'uid'){
					$cellValue=Db::name('member')->where('id',$v2[$v3['Field']])->value('contact');
				}elseif($v3['linkproid'] ==-1){
					if($v3['htmltype']=='radio'){
						$cellValue=Db::name('member')->where('id',$v2[$v3['Field']])->value('contact');
					}else{
						$members=Db::name('member')->where('id in ('.$v2[$v3['Field']].')')->column('contact');
						$cellValue=implode(',', $members);
					}
				}elseif($v3['htmltype']=='checkbox'){
					$cellValue=implode(',', json_decode($v2[$v3['Field']],true));
				}elseif($v3['htmltype']=='datetime' || $v3['Field']=='create_time'){
					$cellValue=date('y-m-d H:i:s',$v2[$v3['Field']]);
				}elseif($v3['Field']=='status'){
					$cellValue=getProgramStat($v2[$v3['Field']]);
				}else{
					$cellValue=$v2[$v3['Field']];
				}
				$sheetObj->setCellValue($cell.$num,$cellValue);
			}
		}
	}
	protected function setLeveBodysLine(){
		$sheetObj=$this->sheetObj;
		$biss=$this->biss;
		if(empty($biss)){
//			throw new \Exception("无Bais数据");
			$this->setBodysLine();
		}else{
			$bisConfig=$this->bisConfig;
			$fieldTit=$this->fieldTit;
			$cellArr=$this->cellArr;			//由头行数据生成
			
			$rel=Db::table('think_pro_tpytic')->where(['linkproid'=>['IN',$biss]])->select();
			if(!$rel){
				throw new \Exception("无数据");
			}
			array_shift($fieldTit);
			foreach($rel as $k=>$v){
				$num=$k+2;
				foreach($fieldTit as $k2=>$v2){
					$sheetObj->setCellValue('A'.$num,$v['linkproid']);
					$cell=$cellArr[$k2+1];
					if($v2['Field'] == 'uid'){
						$cellValue=Db::name('member')->where('id',$v[$v2['Field']])->value('contact');
					}elseif($v2['linkproid'] ==-1){
						if($v2['htmltype']=='radio'){
							$cellValue=Db::name('member')->where('id',$v[$v2['Field']])->value('contact');
						}else{
							$members=Db::name('member')->where('id in ('.$v[$v2['Field']].')')->column('contact');
							$cellValue=implode(',', $members);
						}
					}elseif($v2['htmltype']=='checkbox'){
						$cellValue=implode(',', json_decode($v[$v2['Field']],true));
					}elseif($v2['htmltype']=='datetime' || $v2['Field']=='create_time'){
						$cellValue=date('y-m-d H:i:s',$v[$v2['Field']]);
					}elseif($v2['Field']=='status'){
						$cellValue=getProgramStat($v[$v2['Field']]);
					}else{
						$cellValue=$v[$v2['Field']];
					}
					$sheetObj->setCellValue($cell.$num,$cellValue);
				}
			}
		}
	}
	//导出创建的数据
	protected function export($exportName){
		$excelObj=$this->excelObj;
		export($excelObj,$exportName.date('ymdHis'),'',7,2);
	}
	//获取要导出的程序表需要的字段
	protected function getHeadField(){
		$bisConfig=$this->bisConfig;
		$allField=Db::query('show full fields from think_pro_'.$bisConfig['nid']);		//获取程序的所有字段信息
		array_walk($allField,function(&$val,$key){
			unset($val['Collation']);
			unset($val['Null']);
			unset($val['Key']);
			unset($val['Extra']);
			unset($val['Privileges']);
			unset($val['Default']);
		});
		$attachField=Db::name('programFields')
		->where('pid',$bisConfig['pid'])->column('fnid,isnull,type as htmlType,flist'); //获取程序的录入数据的字段信息
		$fieldTit=[];
		array_walk($allField,function($val,$key) use(&$fieldTit,$bisConfig,$attachField){
			if(!in_array($val['Field'],$bisConfig['desertKey'])){	//排除不需要的字段
				if($val['Field']=='uid'){
					$val['Comment']='创建者';
					$val['backField']='contact';
				}
				$val['linkproid']= isset($attachField[$val['Field']]) ? $attachField[$val['Field']]['flist']: 0;
				$val['htmltype'] = isset($attachField[$val['Field']]) ? $attachField[$val['Field']]['htmlType']: '';
				$val['isnull']   = isset($attachField[$val['Field']]) ? $attachField[$val['Field']]['isnull']: -9;
				$fieldTit[]=$val;
			}
		});
		return $fieldTit;
	}
}